package com.qianniu.napi.admin.web.store;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.FanliActor;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.admin.service.akka.StoreActor;
import com.qianniu.napi.admin.web.goods.entity.GoodsInternetProduct;
import com.qianniu.napi.admin.web.goods.entity.GoodsPackageContent;
import com.qianniu.napi.admin.web.goods.entity.GoodsPurchasingInstructions;
import com.qianniu.napi.admin.web.goods.service.IGoodsInternetProductService;
import com.qianniu.napi.admin.web.goods.service.IGoodsPackageContentService;
import com.qianniu.napi.admin.web.goods.service.IGoodsPurchasingInstructionsService;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.HttpUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 实体店商家地址，需要满足实体营业执照+店面+独立小程序
 * </p>
 *
 * @author chenxuebin
 * @since 2018-10-16
 */
@RestController
public class StoreController {

    private static final Logger logger = LoggerFactory.getLogger(StoreController.class);

    @Autowired
    private IStoreService storeService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsCategoryService goodsCategoryService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsSkuService goodsSkuService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IMerchantAppService merchantAppService;
    @Autowired
    private IMconfigExtService mconfigExtService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private IGoodsfavService goodsfavService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private StoreStatMapper storeStatMapper;
    @Autowired
    private MdpayMapper mdpayMapper;
    @Autowired
    private LeagueMapper leagueMapper;
    @Autowired
    private LeagueMemberMapper leagueMemberMapper;
    @Autowired
    private CoupontplMemberMapper coupontplMemberMapper;
    @Autowired
    private IMaccountService maccountService;
    @Autowired
    private ILeagueMemberService leagueMemberService;
    @Autowired
    private ISaccountService saccountService;
    @Autowired
    private IPyqService pyqService;
    @Autowired
    private IPyqActService pyqActService;
    @Autowired
    private StoreFavorMapper storeFavorMapper;
    @Autowired
    private IFensService fensService;

    @Autowired
    private IGoodsInternetProductService goodsinternetproductService;
    @Autowired
    private IGoodsPackageContentService goodsPackageContentService;
    @Autowired
    private IGoodsPurchasingInstructionsService goodsPurchasingInstructionsService;

    //华口云专用商家详情接口
    @RequestMapping("/api/store/hkyinfo")
    @ResponseBody
    public Jinfo hkystoreinfo(@RequestParam(value = "sid", required = false) Long sid,
                              @RequestParam(value = "isdongtai", required = false) Integer isdongtai,
                              @RequestParam(value = "goods", required = false) String goods,
                              @RequestParam(value = "gid", required = false) String gid
    ) {
        Jinfo info = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        Wrapper<Store> entity = new EntityWrapper<Store>()
                .setSqlSelect("id,address,characteristic,name,zhizhao,info,zhengshu,vrurl,video,is_liansuo isLiansuo,is_parking isParking,is_waimai isWaimai,is_wifi isWifi," +
                        "yzno,yzstatus,gxbno,is_yikatong isYikatong,authno,is_dulizs isDulizs,is_tihuo isTihuo,is_yikatong isYikatong,is_dulizs isDulizs,is_cbct isCbct,pingfen,xuzhi,sellnum,logo,renqi,views,xiangqing," +
                        "is_wxpay isWxpay,is_zfbpay isZfbpay,is_auth isAuth,latitude,linkman,longitude,mlevel,open_hour openHour,phone,phone2,photos,pic,pjprice,price,type,zhutui,xukezheng")
                .eq("mpid", mpid);

        if (sid != null && sid > 0) entity.eq("id", sid);
        Store store = storeService.selectOne(entity);
        if (store == null) return info;

        MerchantApp mapp = redisService.getMApp();

        if (sid != null && sid > 0 && !Strings.isNullOrEmpty(goods) && mapp.getVersion() != null && mapp.getVersion() >= VersionEnum.hangye.getVal()) {
            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", mpid)
                    .eq("sid", sid).eq("state", 1).eq("type", YXType.jifen.getVal()));
            store.setGoods(list);
        }
        Goods good = gid != null ? goodsService.selectById(gid) : null;

        // 商品子表网红单品
        List<GoodsInternetProduct> goodsInternetProductList = goodsinternetproductService.selectList(new EntityWrapper<GoodsInternetProduct>().eq("gid", gid));
        store.setGoodsInternetProductList(goodsInternetProductList);
        // 商品子表套餐内容
        List<GoodsPackageContent> goodsPackageContentList = goodsPackageContentService.selectList(new EntityWrapper<GoodsPackageContent>().eq("gid", gid));
        store.setGoodsPackageContentList(goodsPackageContentList);
        // 商品子表购买须知
        List<GoodsPurchasingInstructions> goodsPurchasingInstructionsList = goodsPurchasingInstructionsService.selectList(new EntityWrapper<GoodsPurchasingInstructions>().eq("gid", gid));
        store.setGoodsPurchasingInstructionsList(goodsPurchasingInstructionsList);
        store.setGood(good);

        //返回是否收藏
        if (ObjectUtil.getUid() != null) {
            int cout = goodsfavService.selectCount(new EntityWrapper<Goodsfav>()
                    .eq("uid", ObjectUtil.getUid())
                    .eq("state", 1)
                    .eq("gid", sid));
            store.setShoucang(cout == 0 ? 0 : 1);
        }
        //返回商家快讯列表
        store.setNews(newsService.selectList(new EntityWrapper<News>().eq("mpid", mpid).eq("sid", sid).eq("state", 1)));

        //返回商家促销活动
        String[] stas = new String[]{"0", "2"};
        store.setHuodong(goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", mpid)
                .eq("sid", sid).eq("state", 1).ge("type", 1)
                .ne("type", 4).in("status", stas).orderBy("id", false)
        ));

        //返回商家动态
        if (isdongtai != null) {
            Page page = new Page(1, 10);
            Page<Pyq> pages = pyqService.selectPage(page, new EntityWrapper<Pyq>()
                    .eq("sid", sid)
                    .eq("state", 1).orderBy("id", false));

            List<Pyq> list = pages.getRecords();
            Page page2 = new Page(1, 50);
            for (Pyq item : list) {

                Page<PyqAct> plist = pyqActService.selectPage(page2, new EntityWrapper<PyqAct>()
                        .eq("mpid", ObjectUtil.getMpid())
                        .eq("act", 1)
                        .eq("pyqid", item.getId())
                        .eq("state", 1)
                        .orderBy("hid", true)
                        .orderBy("id", false));

                item.setHuifus(plist == null ? null : plist.getRecords());

                List<PyqAct> zans = pyqActService.selectList(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                        .eq("mpid", ObjectUtil.getMpid())
                        .eq("act", 2)
                        .eq("pyqid", item.getId())
                        .orderBy("id", true));

                PyqAct zan = pyqActService.selectOne(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                        .eq("uid", ObjectUtil.getUid())
                        .eq("mpid", ObjectUtil.getMpid())
                        .eq("act", 2)
                        .eq("pyqid", item.getId())
                        .orderBy("id", true));
                if (zan != null) item.setSelf(1);
                else item.setSelf(0);

                item.setZans(zans);

//                int views = pyqActService.selectCount(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
//                        .eq("mpid", ObjectUtil.getMpid())
//                        .eq("act", 3)
//                        .eq("pyqid", item.getId())
//                        .orderBy("id", true));
//                item.setViews(views);
            }
            info.setExtra(list);
        }

        //判断会员
        //是门诊会员
        int level = 1;
        LeagueMember lmmember = new LeagueMember();
        if (uid != null) {
            List<LeagueMember> lmmembers = leagueMemberMapper.selectList(new EntityWrapper<LeagueMember>()
                    .eq("uid", uid).eq("sid", sid).orderBy("mlevel", false));
            if (lmmembers != null && !lmmembers.isEmpty()) {
                info.setCout(1);
                lmmember = lmmembers.get(0);
                level = lmmember.getMlevel();
            } else {
                info.setCout(0);
                lmmember.setMlevel(0);
            }
        } else {
            info.setCout(0);
            lmmember.setMlevel(0);
        }

        //判断是否收藏
        int favor = storeFavorMapper.selectCount(new EntityWrapper<StoreFavor>().eq("uid", uid).eq("sid", sid));
        store.setShoucang(favor);

        int cout = leagueMemberMapper.selectCount(new EntityWrapper<LeagueMember>().eq("shareid", uid).eq("sid", sid));
        lmmember.setFens(cout);
//        List<CoupontplMember> coupontplMembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
//                .ge("mlevel", level)
//                .le("mlevel", level + 1)
//                .eq("sid", sid));
//        String mquanyi = "";
//        String xiamquanyi = "";
//        for (CoupontplMember item : coupontplMembers) {
//            if (item.getMlevel().intValue() == level) {
//                mquanyi += item.getMquanyi() + "+";
//            }
//            if (item.getMlevel().intValue() == level + 1) {
//                xiamquanyi += item.getMquanyi() + "+";
//            }
//        }
//        if (coupontplMembers.size() > 0) {
//            if (mquanyi != null && mquanyi.endsWith("+")) mquanyi = mquanyi.substring(0, mquanyi.length() - 1);
//            if (xiamquanyi != null && xiamquanyi.endsWith("+"))
//                xiamquanyi = xiamquanyi.substring(0, xiamquanyi.length() - 1);
//            lmmember.setMquanyi(mquanyi);
//            lmmember.setXiamquanyi(xiamquanyi);
//            info.setData(lmmember);
//        }
        info.setData(lmmember);
        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_STORE_VIEW + "@" + store.getId(), ActorRef.noSender());

        info.setInfo(store);
        return info;
    }

    @RequestMapping("/api/store/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = storeService.selectPage(page, new EntityWrapper<Store>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    //获取盟主下属商家
    @RequestMapping("/api/store/lmlist")
    @ResponseBody
    public Jinfo lmlist(@RequestParam(value = "sids", required = false) String sids,
                        HttpServletRequest req) {
        Jinfo info = new Jinfo();
        List<String> ids = new ArrayList<String>();
        if (!Strings.isNullOrEmpty(sids)) {
            ids = Arrays.asList(sids.split(","));
        }

        Wrapper<Store> entity = new EntityWrapper<Store>()
                .setSqlSelect("id,name")
                .eq("mpid", ObjectUtil.getMpid())
                .eq("leagueid", ObjectUtil.getSid())
                .eq("state", 1);
        if (ids.size() > 0) entity.notIn("id", ids);

        List<Store> list = storeService.selectList(entity);
        for (Store item : list) {
            item.setCouponTpls(couponTplService.selectList(new EntityWrapper<CouponTpl>()
                    .eq("state", 1).eq("sid", item.getId())));
        }
        info.setInfo(list);
        return info;
    }

    @RequestMapping("/api/store/nearby/list")
    @ResponseBody
    public Jinfo getNearbyStores(@RequestParam(value = "gid", required = false) Long gid,
                                 @RequestParam(value = "hyid", required = false) Long hyid,
                                 @RequestParam(value = "lat") double lat,
                                 @RequestParam(value = "lng") double lng,
                                 @RequestParam(value = "sou", required = false) String sou,
                                 @RequestParam(value = "sort", required = false) String sort,
                                 @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                 @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                 HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
//        long mid = gid!=null&&gid>0?ObjectUtil.getMid():0;
        Long mpid = ObjectUtil.getMpid();
        if (mpid == 11 && hyid != null && (hyid.intValue() == 139 || hyid.intValue() == 140)) hyid = 3938l;
        logger.debug("-----------------------------------hyid=" + hyid);
        List<Store> list = storeService.getNearbyStores(pageIndex, pageSize, hyid, lat, lng, ObjectUtil.getMpid(), null, sort, sou);
        info.setInfo(list);
        return info;
    }


    /**
     * 华口云专属
     **/
    @RequestMapping("/api/store/nearby/hkylist")
    @ResponseBody
    public Jinfo getNearbyHkyStores(@RequestParam(value = "gid", required = false) Long gid,
                                    @RequestParam(value = "hyid", required = false) Long hyid,
                                    @RequestParam(value = "lat") double lat,
                                    @RequestParam(value = "lng") double lng,
                                    @RequestParam(value = "fenlei", required = false) String fenlei,
                                    @RequestParam(value = "sou", required = false) String sou,
                                    @RequestParam(value = "sort", required = false) String sort,
                                    @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                    @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Long mpid = ObjectUtil.getMpid();
        if (mpid == 11 && hyid != null && (hyid.intValue() == 139 || hyid.intValue() == 140)) hyid = 3938l;
        logger.debug("-----------------------------------hyid=" + hyid);
        List<Store> list = storeService.getNearbyStores(pageIndex, pageSize, hyid, lat, lng, ObjectUtil.getMpid(), fenlei, sort, sou);
        info.setInfo(list);
        return info;
    }

    /**
     * 华口云专属，过滤商品相关商家
     **/
    @RequestMapping("/api/store/nearby/glist")
    @ResponseBody
    public Jinfo getNearbygStores(@RequestParam(value = "gid", required = false) String sgid,
                                  @RequestParam(value = "lat") double lat,
                                  @RequestParam(value = "lng") double lng,
                                  @RequestParam(value = "sort", required = false) String sort,
                                  @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                  @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                  HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        sgid = sgid.replace("undefined", "");
        Long gid = Strings.isNullOrEmpty(sgid) ? null : Long.valueOf(sgid);
        Goods goods = gid != null ? goodsService.selectById(gid) : null;
        Map<String, Double> map = new HashMap<String, Double>();
        if (goods != null && goods.getFanwei() != null) map.put("fanwei", Double.valueOf(goods.getFanwei()));
        else map.put("fanwei", 0d);

        if (goods != null && goods.getFanwei() != null && lat == 0) {
            info.setExtra(100);
            info.setMap(map);
        }
        if (gid == null) gid = 0l;
        List<Store> list = storeService.getNearbyHYStores(pageIndex, pageSize, lat, lng, ObjectUtil.getMpid(), gid, sort);
        if (list == null) list = new ArrayList<>();

        for (Store item : list) {
            if (goods != null && goods.getFanwei() != null && item.getDistance() < goods.getFanwei()) {
                info.setData(100);
                map.put("distance", item.getDistance());
                info.setMap(map);
            }
        }

        info.setInfo(list);
        return info;
    }

    /**
     * 过滤行业相关商家
     **/
    @RequestMapping("/api/store/hylist")
    @ResponseBody
    public Jinfo getHyStores(@RequestParam(value = "hyid") Long hyid,
                             @RequestParam(value = "renzheng", required = false) Long renzheng,
                             @RequestParam(value = "lat") String lat,
                             @RequestParam(value = "lng") String lng,
                             @RequestParam(value = "sort", required = false) String sort,
                             @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                             @RequestParam(value = "pageSize", required = false) Integer pageSize,
                             HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        if (renzheng == null) renzheng = 0l;
//        long mid = gid!=null&&gid>0?ObjectUtil.getMid():0;
        Long mpid = ObjectUtil.getMpid();
        MconfigExt mconfigExt = mconfigExtService.selectById(mpid);
        logger.debug("========================mconfigExt=" + JSON.toJSONString(mconfigExt));
        Double latt = null;
        Double lngt = null;
        if (Strings.isNullOrEmpty(lat) || lat.equals("undefined")) {
            latt = mconfigExt.getLat();// default
        } else {
            latt = Double.parseDouble(lat);
        }
        if (Strings.isNullOrEmpty(lng) || lng.equals("undefined")) {
            lngt = mconfigExt.getLng();// default
        } else {
            lngt = Double.parseDouble(lng);
        }
        // 116.405218,39.913891
        if (latt == null) {
            latt = 116.405218;
        }
        if (lngt == null) {
            latt = 39.913891;
        }

        List<Store> list = storeService.getHyStores(pageIndex, pageSize, latt, lngt, ObjectUtil.getMpid(), sort, hyid, renzheng);
        info.setInfo(list);
        return info;
    }

    @RequestMapping("/api/store/shlist")
    @ResponseBody
    public Jinfo shlist(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "sousuo", required = false) String sousuo,
                        @RequestParam(value = "guanlian", required = false) Integer guanlian,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);

        Wrapper<Store> wrapper = new EntityWrapper<Store>()
                .setSqlSelect("id,name,address,latitude,longitude,logo,type,typename,characteristic,pic,mlevel,state,status,pingfen,modifytime");
        if (!Strings.isNullOrEmpty(sousuo)) {
            wrapper.like("name", sousuo);
        }
        if (guanlian != null && guanlian == 1) {
            wrapper.isNull("uid");
        }

        wrapper.eq("mpid", ObjectUtil.getMpid())
                .orderBy("modifytime", false);

        Page<Store> list = storeService.selectPage(page, wrapper);
        List<Store> slist = list.getRecords();
        Map<String, String> map = new HashMap<String, String>();
        String srkey = null;

        for (Store store : slist) {
            store.setTypeName(Constants.HY_TYPE_MAP.get(store.getType()));
//            srkey = Constants.REDIS_STORE + store.getId();
//            注释setGluser
//            User rsuser = redisService.get(srkey);
//            if(rsuser != null) store.setGluser(redisService.get(srkey));
        }

        info.setInfo(list.getRecords());
        return info;
    }

    @RequestMapping("/api/store/shenhe")
    @ResponseBody
    public Jinfo shenhe(@RequestParam(value = "sid") Long sid, @RequestParam(value = "status") Integer status) {
        Jinfo info = new Jinfo();
        Store store = storeService.selectById(sid);
        if (store == null) {
            info.setCode(4);
            info.setMsg("商家信息不存在");
            return info;
        }

        if (status == null || status < 1 || status > 3) {
            info.setCode(1);
            info.setMsg("参数非法");
            return info;
        }

        Store ustore = new Store();
        ustore.setId(sid);
        ustore.setStatus(status);
        if (status == 2) {//审核通过
            User user = new User();
            if (store.getUid() == null && !Strings.isNullOrEmpty(store.getPhone())) {
                user = userService.selectOne(new EntityWrapper<User>()
                        .eq("phone", store.getPhone())
                        .eq("mpid", store.getMpid())
                );

            } else if (store.getUid() != null) {
                user = userService.selectById(store.getUid());
            }
            if (user != null) {
                store.setUid(user.getId());
                store.updateById();
            } else {
                info.setCode(1);
                info.setMsg("店铺用户信息关联失败");
                return info;
            }

            ustore.setState(1);
            user.setIsMch(1);
            user.setUtype(Hytype.merchant.getVal());
            user.setIsAgent(-1);
            user.setIsPlatform(-1);
            user.setIsAdmin(1);
            user.setMemberLevel(1);
            user.setSid(sid);
            user.setModifytime(new Date());
            user.updateById();
            redisService.delUser(user.getId());

            //初始化saccountService
            Saccount saccount = saccountService.selectById(sid);
            if (saccount == null) {
                saccountService.initSaccount(store.getMid(), store.getMpid(), store.getId(), store.getLeagueid());
            }
        }
        ustore.setModifier(ObjectUtil.getUid());
        ustore.setModifytime(new Date());
        ustore.updateById();

        ustore.setName(store.getName());
        ustore.setAddress(store.getAddress());
        ustore.setPic(store.getPic());
        ustore.setType(store.getType());
        info.setInfo(ustore);

        // 华口云审核 需要初始化数据
//        if(ObjectUtil.getMpid() ==11){
//            List<GoodsCategory> categories = goodsCategoryService.selectList(new EntityWrapper<GoodsCategory>().ge("id",139).le("id",148));
//            Goods goods139 = goodsService.selectOne(new EntityWrapper<Goods>().ge("cid",139).eq("sid",142));
//
//            List<Goods> goods141 = goodsService.selectList(new EntityWrapper<Goods>().ge("cid",141).eq("sid",142));
//            List<Goods> goods142 = goodsService.selectList(new EntityWrapper<Goods>().ge("cid",142).eq("sid",142));
//
//            List<Goods> goods144 = goodsService.selectList(new EntityWrapper<Goods>().ge("cid",144).eq("sid",142));
//            List<Goods> goods145 = goodsService.selectList(new EntityWrapper<Goods>().ge("cid",145).eq("sid",142));
//            List<Goods> goods146 = goodsService.selectList(new EntityWrapper<Goods>().ge("cid",146).eq("sid",142));
//            List<Goods> goods147 = goodsService.selectList(new EntityWrapper<Goods>().ge("cid",147).eq("sid",142));
//            List<Goods> goods148 = goodsService.selectList(new EntityWrapper<Goods>().ge("cid",148).eq("sid",142));
//
//            List<GoodsSku> goodsSku = goodsSkuService.selectList(new EntityWrapper<GoodsSku>().eq("cid",139).eq("sid",142));
//
//            for (GoodsCategory item: categories){
//
//                if(item.getId()==140){
//                    continue;
//                }
//
//                if(item.getId()==139){
//
//                    goods139.setId(null);
//                    goods139.setSid(sid);
//                    goods139.setCreatetime(new Date());
//                    goods139.setModifytime(new Date());
//                    goods139.insert();
//
//                    for(GoodsSku gu: goodsSku){
//                        gu.setId(null);
//                        gu.setGid(goods139.getId());
//                        gu.setSid(sid);
//                        gu.setCreatetime(new Date());
//                        gu.setModifytime(new Date());
//                        gu.insert();
//                    }
//
//                } else if(item.getId()==141){
//                    for(Goods g: goods141){
//                        g.setId(null);
//                        g.setSid(sid);
//                        g.setCreatetime(new Date());
//                        g.setModifytime(new Date());
//                        g.insert();
//                    }
//                } else if(item.getId()==142){
//                    for(Goods g: goods142){
//                        g.setId(null);
//                        g.setSid(sid);
//                        g.setCreatetime(new Date());
//                        g.setModifytime(new Date());
//                        g.insert();
//                    }
//                } else if(item.getId()==144){
//                    for(Goods g: goods144){
//                        g.setId(null);
//                        g.setSid(sid);
//                        g.setCreatetime(new Date());
//                        g.setModifytime(new Date());
//                        g.insert();
//                    }
//                } else if(item.getId()==145){
//                    for(Goods g: goods145){
//                        g.setId(null);
//                        g.setSid(sid);
//                        g.setCreatetime(new Date());
//                        g.setModifytime(new Date());
//                        g.insert();
//                    }
//                } else if(item.getId()==146){
//                    for(Goods g: goods146){
//                        g.setId(null);
//                        g.setSid(sid);
//                        g.setCreatetime(new Date());
//                        g.setModifytime(new Date());
//                        g.insert();
//                    }
//                } else if(item.getId()==147){
//                    for(Goods g: goods147){
//                        g.setId(null);
//                        g.setSid(sid);
//                        g.setCreatetime(new Date());
//                        g.setModifytime(new Date());
//                        g.insert();
//                    }
//                } else if(item.getId()==148){
//                    for(Goods g: goods148){
//                        g.setId(null);
//                        g.setSid(sid);
//                        g.setCreatetime(new Date());
//                        g.setModifytime(new Date());
//                        g.insert();
//                    }
//                }
//            }
//        }

        return info;
    }

    @RequestMapping("/api/store/shangjia")
    @ResponseBody
    public Jinfo shajia(@RequestParam(value = "sid") Long sid, @RequestParam(value = "state") Integer state) {
        Jinfo info = new Jinfo();
        Store store = storeService.selectById(sid);
        if (store == null) {
            info.setCode(4);
            info.setMsg("商家信息不存在");
            return info;
        }

        if (state == null || (state != -1 && state != 1)) {
            info.setCode(1);
            info.setMsg("参数非法");
            return info;
        }

        Store ustore = new Store();
        ustore.setId(sid);
        ustore.setState(state);
        ustore.setModifier(ObjectUtil.getUid());
        ustore.setModifytime(new Date());
        ustore.updateById();

        ustore.setName(store.getName());
        ustore.setAddress(store.getAddress());
        ustore.setPic(store.getPic());
        ustore.setType(store.getType());
        info.setInfo(ustore);

        return info;
    }

    @RequestMapping("/api/store/add")
    @ResponseBody
    public Jinfo storeAdd(@Valid Store store) {
        Jinfo info = new Jinfo();
        if (ObjectUtil.getUid() == null) {
            info.setMsg("请授权登录之后再操作");
            info.setCode(1);
            return info;
        }
        store.setOpenHour(store.getOpenHour().replaceAll("；", ":"));
        store.setOpenHour(store.getOpenHour().replaceAll("：", ":"));
        //校验重复
        Integer cout = storeService.selectCount(new EntityWrapper<Store>().eq("uid", ObjectUtil.getUid()));
        if (cout > 1 && store.getId() == null) {
            info.setMsg("您已提交商家入驻，请勿重复提交");
            info.setCode(1);
            return info;
        }

        store.setCreatetime(new Date());
        store.setModifytime(new Date());
        store.setMid(ObjectUtil.getMid());
        store.setMpid(ObjectUtil.getMpid());
        store.setUid(ObjectUtil.getUid());
        store.setModifytime(new Date());

        if (!Strings.isNullOrEmpty(store.getPhotos()) && Strings.isNullOrEmpty(store.getPic())) {
            List<String> pics = Arrays.asList(store.getPhotos().split(";"));
            store.setPic(pics.get(0));
        }
        store.setThumb(store.getPic());
        store.insertOrUpdate();
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Store@" + store.getId() + "@update", ActorRef.noSender());

        StoreStat storeStat = new StoreStat();
        storeStat.setStoreid(store.getId());
        storeStat.setStorename(store.getName());
        storeStat.setStorepic(store.getPic());
        storeStat.setModifytime(store.getCreatetime());
        storeStat.setMpid(store.getMpid());
        storeStat.insertOrUpdate();

        //关联用户
        User user = new User();
        user.setId(ObjectUtil.getUid());
        user.setSid(store.getId());
        user.setSlevel(0);
        user.updateById();

        redisService.delUser(user.getId());

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_STORE_MODIFY + "@" + store.getId(), ActorRef.noSender());

        return info;
    }

    @RequestMapping("/api/store/modify")
    @ResponseBody
    public Jinfo storeUpdate(Store store) {
        Jinfo info = new Jinfo();
        store.setModifytime(new Date());
        store.setUid(ObjectUtil.getUid());
        if (!Strings.isNullOrEmpty(store.getPhotos())) {
            List<String> pics = Arrays.asList(store.getPhotos().split(";"));
            store.setPic(pics.get(0));
        }
        store.updateById();

        //更新素材资源
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Store@" + store.getId() + "@update", ActorRef.noSender());

        StoreStat storeStat = new StoreStat();
        storeStat.setStoreid(store.getId());
        storeStat.setStorename(store.getName());
        storeStat.setStorepic(store.getThumb());
        storeStat.setModifytime(new Date());
        storeStat.setMpid(store.getMpid());
        storeStat.insertOrUpdate();

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_STORE_MODIFY + "@" + store.getId(), ActorRef.noSender());
        return info;
    }

    @RequestMapping("/api/store/detail")
    @ResponseBody
    public Jinfo getStoreDetailById(@RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        Store store = storeService.selectById(id);
        info.setInfo(store);
        return info;
    }

    @RequestMapping("/api/store/rzshenhe")
    @ResponseBody
    public Jinfo rzshenhe(@RequestParam("pingfen") int pingfen,
                          @RequestParam("sid") long sid,
                          HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        User user = redisService.getUser();
        if (user.getIsPlatform() == null || user.getIsPlatform() != 1) {
            info.setCode(1);
            info.setMsg("当前用户无权限操作");
            return info;
        }

        Store store = storeService.selectById(sid);
        if (store == null) {
            info.setCode(4);
            info.setMsg("参数有误");
            return info;
        }
        if (pingfen < 1 || pingfen > 5) {
            info.setCode(4);
            info.setMsg("参数有误");
            return info;
        }
        Store nstore = new Store();
        nstore.setId(sid);
        nstore.setPingfen(pingfen);
        nstore.setModifier(ObjectUtil.getUid());
        nstore.setModifytime(new Date());
        nstore.updateById();

        return info;
    }

    @RequestMapping("/api/store/info")
    @ResponseBody
    public Jinfo storeinfo(@RequestParam(value = "sid", required = false) Long sid,
                           @RequestParam(value = "isdongtai", required = false) Integer isdongtai,
                           @RequestParam(value = "goods", required = false) String goods) {
        Jinfo info = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        Wrapper<Store> entity = new EntityWrapper<Store>()
                .setSqlSelect("id,address,characteristic,name,zhizhao,info,vrurl,zhengshu,video,is_liansuo isLiansuo,is_parking isParking,is_waimai isWaimai,is_wifi isWifi," +
                        "is_tihuo isTihuo,is_yikatong isYikatong,is_dulizs isDulizs,is_cbct isCbct,pingfen,xuzhi,sellnum,logo,renqi,views,xiangqing," +
                        "is_wxpay isWxpay,is_zfbpay isZfbpay,is_auth isAuth,latitude,linkman,longitude,open_hour openHour,phone,phone2,photos,pic,pjprice,price,type,zhutui,xukezheng")
                .eq("mpid", mpid);

        if (sid != null && sid > 0) entity.eq("id", sid);
        Store store = storeService.selectOne(entity);
        if (store == null) return info;

        MerchantApp mapp = redisService.getMApp();

        if (sid != null && sid > 0 && !Strings.isNullOrEmpty(goods) && mapp.getVersion() != null && mapp.getVersion() >= VersionEnum.hangye.getVal()) {
            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", mpid)
                    .eq("sid", sid).eq("state", 1).eq("type", YXType.jifen.getVal()));
            store.setGoods(list);
        }
        //返回是否收藏
        if (ObjectUtil.getUid() != null) {
            int cout = goodsfavService.selectCount(new EntityWrapper<Goodsfav>()
                    .eq("uid", ObjectUtil.getUid())
                    .eq("state", 1)
                    .eq("gid", sid));
            store.setShoucang(cout == 0 ? 0 : 1);
        }
        //返回商家快讯列表
        store.setNews(newsService.selectList(new EntityWrapper<News>().eq("mpid", mpid).eq("sid", sid).eq("state", 1)));

        //返回商家促销活动
        String[] stas = new String[]{"0", "2"};
        store.setHuodong(goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", mpid)
                .eq("sid", sid).eq("state", 1).ge("type", 1)
                .ne("type", 4).in("status", stas).orderBy("id", false)
        ));

        //返回商家动态
        if (isdongtai != null) {
            Page page = new Page(1, 10);
            Page<Pyq> pages = pyqService.selectPage(page, new EntityWrapper<Pyq>()
                    .eq("sid", sid)
                    .eq("state", 1).orderBy("id", false));

            List<Pyq> list = pages.getRecords();
            Page page2 = new Page(1, 50);
            for (Pyq item : list) {

                Page<PyqAct> plist = pyqActService.selectPage(page2, new EntityWrapper<PyqAct>()
                        .eq("mpid", ObjectUtil.getMpid())
                        .eq("act", 1)
                        .eq("pyqid", item.getId())
                        .eq("state", 1)
                        .orderBy("hid", true)
                        .orderBy("id", false));

                item.setHuifus(plist == null ? null : plist.getRecords());

                List<PyqAct> zans = pyqActService.selectList(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                        .eq("mpid", ObjectUtil.getMpid())
                        .eq("act", 2)
                        .eq("pyqid", item.getId())
                        .orderBy("id", true));

                PyqAct zan = pyqActService.selectOne(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
                        .eq("uid", ObjectUtil.getUid())
                        .eq("mpid", ObjectUtil.getMpid())
                        .eq("act", 2)
                        .eq("pyqid", item.getId())
                        .orderBy("id", true));
                if (zan != null) item.setSelf(1);
                else item.setSelf(0);

                item.setZans(zans);

//                int views = pyqActService.selectCount(new EntityWrapper<PyqAct>().setSqlSelect("id,uid,name,logo")
//                        .eq("mpid", ObjectUtil.getMpid())
//                        .eq("act", 3)
//                        .eq("pyqid", item.getId())
//                        .orderBy("id", true));
//                item.setViews(views);
            }
            info.setExtra(list);
        }

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_STORE_VIEW + "@" + store.getId(), ActorRef.noSender());

        info.setInfo(store);
        return info;
    }



    //联盟版商家信息街某
    @RequestMapping("/api/store/infohy")
    @ResponseBody
    public Jinfo storeinfohy(@RequestParam(value = "sid", required = false) Long sid,
                             @RequestParam(value = "goods", required = false) String goods) {
        Jinfo info = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        Wrapper<Store> entity = new EntityWrapper<Store>()
                .setSqlSelect("id,address,characteristic,name,zhizhao,info,video,is_liansuo isLiansuo,is_parking isParking,is_waimai isWaimai,is_wifi isWifi," +
                        "is_tihuo isTihuo,is_yikatong isYikatong,is_dulizs isDulizs,is_cbct isCbct,pingfen,xuzhi,sellnum,logo,renqi,views,xiangqing,leagueid,wxno,phone,youhui, " +
                        "is_wxpay isWxpay,is_zfbpay isZfbpay,is_auth isAuth,latitude,linkman,longitude,open_hour openHour,phone,phone2,photos,pic,pjprice,price,type,zhutui,xukezheng")
                .eq("mpid", mpid);

        if (sid != null && sid > 0) entity.eq("id", sid);
        Store store = storeService.selectOne(entity);
        if (store == null) return info;

        MerchantApp mapp = redisService.getMApp();

        if (sid != null && sid > 0 && !Strings.isNullOrEmpty(goods) && mapp.getVersion() != null && mapp.getVersion() >= VersionEnum.hangye.getVal()) {
            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", mpid)
                    .eq("sid", sid).eq("state", 1).eq("type", YXType.jifen.getVal()));
            store.setGoods(list);
        }
        //返回是否收藏
        if (uid != null) {
            int cout = goodsfavService.selectCount(new EntityWrapper<Goodsfav>()
                    .eq("uid", ObjectUtil.getUid())
                    .eq("state", 1)
                    .eq("gid", sid));
            store.setShoucang(cout == 0 ? 0 : 1);
        }

        //返回商家快讯列表
        store.setNews(newsService.selectList(new EntityWrapper<News>()
                .eq("mpid", mpid).eq("sid", sid)
                .eq("state", 1)));

        //返回商家促销活动
        String[] stas = new String[]{"0", "2"};
        store.setHuodong(goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", mpid)
                .eq("sid", sid).eq("state", 1).ge("type", 1)
                .ne("type", 4).in("status", stas).orderBy("id", false)
        ));

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_STORE_VIEW + "@" + store.getId(), ActorRef.noSender());

        //判断会员
        if (uid != null) {
            List<LeagueMember> lmmembers = leagueMemberMapper.selectList(new EntityWrapper<LeagueMember>()
                    .eq("uid", uid).eq("sid", sid)
                    .orderBy("mlevel", false)
            );

            if (lmmembers != null && lmmembers.size() > 0) {
                LeagueMember lmmember = lmmembers.get(0);
                int level = lmmember.getMlevel();
                List<CoupontplMember> coupontplMembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
                        .ge("mlevel", level)
                        .le("mlevel", level + 1)
                        .eq("sid", lmmember.getSid()));
                String mquanyi = "";
                String xiamquanyi = "";
                ;
                for (CoupontplMember item : coupontplMembers) {
                    if (item.getMlevel().intValue() == level) {
                        mquanyi += item.getMquanyi() + "+";
                    }
                    if (item.getMlevel().intValue() == level + 1) {
                        xiamquanyi += item.getMquanyi() + "+";
                    }
                }
                if (coupontplMembers.size() > 0) {
                    if (mquanyi != null && mquanyi.endsWith("+")) mquanyi = mquanyi.substring(0, mquanyi.length() - 1);
                    if (xiamquanyi != null && xiamquanyi.endsWith("+"))
                        xiamquanyi = xiamquanyi.substring(0, xiamquanyi.length() - 1);
                    lmmember.setMquanyi(mquanyi);
                    lmmember.setXiamquanyi(xiamquanyi);
                    info.setExtra(lmmember);
                }
            }
        }

        //判断商品个数，如果没有，前端则不显示商城
        int cout = goodsService.selectCount(new EntityWrapper<Goods>().eq("sid", sid)
                .eq("type", 0).eq("state", 1).eq("status", 2));
        info.setCout(cout);
        info.setInfo(store);
        return info;
    }

    //联盟版商家信息街某
    @RequestMapping("/api/store/mchinfo")
    @ResponseBody
    public Jinfo mchinfo(@RequestParam(value = "sid", required = false) Long sid,
                         @RequestParam(value = "goods", required = false) String goods) {
        Jinfo info = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        if (sid == null) sid = ObjectUtil.getSid();

        Wrapper<Store> entity = new EntityWrapper<Store>()
                .setSqlSelect("id,address,characteristic,name,zhizhao,info,video,is_liansuo isLiansuo,is_parking isParking,is_waimai isWaimai,is_wifi isWifi," +
                        "is_tihuo isTihuo,is_yikatong isYikatong,is_dulizs isDulizs,is_cbct isCbct,pingfen,xuzhi,sellnum,logo,renqi,views,xiangqing,leagueid,wxno,phone,youhui, " +
                        "is_wxpay isWxpay,is_zfbpay isZfbpay,is_auth isAuth,latitude,linkman,longitude,open_hour openHour,phone,phone2,photos,pic,pjprice,price,type,zhutui,xukezheng")
                .eq("mpid", mpid);

        if (sid != null && sid > 0) entity.eq("id", sid);
        Store store = storeService.selectOne(entity);
        if (store == null) return info;

        MerchantApp mapp = redisService.getMApp();

        if (sid != null && sid > 0 && !Strings.isNullOrEmpty(goods) && mapp.getVersion() != null && mapp.getVersion() >= VersionEnum.hangye.getVal()) {
            List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", mpid)
                    .eq("sid", sid).eq("state", 1).eq("type", YXType.jifen.getVal()));
            store.setGoods(list);
        }
        //返回是否收藏
        if (uid != null) {
            int cout = goodsfavService.selectCount(new EntityWrapper<Goodsfav>()
                    .eq("uid", ObjectUtil.getUid())
                    .eq("state", 1)
                    .eq("gid", sid));
            store.setShoucang(cout == 0 ? 0 : 1);
        }
        //返回商家快讯列表
        store.setNews(newsService.selectList(new EntityWrapper<News>().eq("mpid", mpid).eq("sid", sid).eq("state", 1)));

        //返回商家促销活动
        String[] stas = new String[]{"0", "2"};
        store.setHuodong(goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", mpid)
                .eq("sid", sid).eq("state", 1).ge("type", 1)
                .ne("type", 4).in("status", stas).orderBy("id", false)
        ));

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_STORE_VIEW + "@" + store.getId(), ActorRef.noSender());

        //判断会员
        if (uid != null) {
            List<LeagueMember> lmmembers = leagueMemberMapper.selectList(new EntityWrapper<LeagueMember>()
                    .eq("uid", uid).eq("sid", sid)
                    .orderBy("mlevel", false)
            );

            if (lmmembers != null && lmmembers.size() > 0) {
                LeagueMember lmmember = lmmembers.get(0);
                int level = lmmember.getMlevel();
                List<CoupontplMember> coupontplMembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
                        .ge("mlevel", level)
                        .le("mlevel", level + 1)
                        .eq("sid", lmmember.getSid()));
                String mquanyi = "";
                String xiamquanyi = "";
                for (CoupontplMember item : coupontplMembers) {
                    if (item.getMlevel().intValue() == level) {
                        mquanyi += item.getMquanyi() + "+";
                    }
                    if (item.getMlevel().intValue() == level + 1) {
                        xiamquanyi += item.getMquanyi() + "+";
                    }
                }
                if (coupontplMembers.size() > 0) {
                    if (mquanyi != null && mquanyi.endsWith("+")) mquanyi = mquanyi.substring(0, mquanyi.length() - 1);
                    if (xiamquanyi != null && xiamquanyi.endsWith("+"))
                        xiamquanyi = xiamquanyi.substring(0, xiamquanyi.length() - 1);
                    lmmember.setMquanyi(mquanyi);
                    lmmember.setXiamquanyi(xiamquanyi);
                    info.setExtra(lmmember);
                }
            }
        }

        //判断商品个数，如果没有，前端则不显示商城
        int cout = goodsService.selectCount(new EntityWrapper<Goods>().eq("sid", sid)
                .eq("type", 0).eq("state", 1).eq("status", 2));
        info.setCout(cout);
        info.setInfo(store);
        return info;
    }

    @RequestMapping("/api/store/cxqsjlist")
    @ResponseBody
    public Jinfo cxsjlist() {

        Jinfo info = new Jinfo();

        Long mpid = ObjectUtil.getMpid();

        Wrapper<CouponTpl> centity = new EntityWrapper<CouponTpl>().setSqlSelect("sid,count(1) as repeatNum").eq("mpid", mpid).isNotNull("sid").groupBy("sid");
        List<CouponTpl> couponTpls = couponTplService.selectList(centity);
        if (couponTpls == null || couponTpls.size() == 0) {
            return info;
        }

        List<String> sids = new ArrayList<String>();
        for (CouponTpl item : couponTpls) {
            if (item.getSid() != null && item.getSid() > 0) sids.add(item.getSid().toString());
        }

        Wrapper<Store> sentity = new EntityWrapper<Store>()
                .setSqlSelect("id,name,logo,address")
                .in("id", sids)
                .eq("mpid", ObjectUtil.getMpid());

        List<Store> store = storeService.selectList(sentity);
        if (store == null) return info;

        info.setInfo(store);
        return info;
    }


    @RequestMapping("/api/store/wifi")
    @ResponseBody
    public Jinfo storewifi() {

        Jinfo info = new Jinfo();
        Wrapper<Store> entity = new EntityWrapper<Store>()
                .setSqlSelect("id,wifiname,wifipwd")
                .eq("mpid", ObjectUtil.getMpid());
        Store store = storeService.selectOne(entity);
        info.setInfo(store);
        return info;
    }

    @RequestMapping("/api/store/getinfobyscene")
    @ResponseBody
    public Jinfo getinfobyscene(String scene) {
        Jinfo info = new Jinfo();

        if (Strings.isNullOrEmpty(scene)) {
            info.setCode(4);
            info.setMsg("参数错误");
            return info;
        }
        String[] scenes = scene.split("_");
        String rkey = Constants.REDIS_APP_USER + ObjectUtil.getMpid() + "_" + scenes[0];
        User ruser = redisService.get(rkey);
        Long storeid = null;
        if (ruser == null) {
            ruser = userService.selectById(scenes[0]);
            storeid = ruser.getSid();
        } else {
            storeid = ruser.getSid();
        }

        logger.info("--------------------------------------storeid=" + storeid);
        if (storeid == null) {
            info.setCode(1);
            info.setMsg("当前码非商户收款码");
            return info;
        }

        Store store = storeService.selectById(storeid);
        if (store == null) {
            info.setCode(4);
            info.setMsg("商户不存在");
            return info;
        }
        logger.info("--------------------------------------store=" + JSON.toJSONString(store));

        Map map = new HashMap<String, String>();
        map.put("storename", store.getName());
        map.put("photo", store.getThumb() == null ? store.getPic() : store.getThumb());
        map.put("zhekou", store.getZhekou());
        map.put("jffanbi", store.getJffanbi());

        info.setInfo(map);
        return info;
    }

    @RequestMapping("/api/store/jfpay")
    @ResponseBody
    public Jinfo jfpay(String scene, BigDecimal jfcout) {
        Jinfo info = new Jinfo();

        if (Strings.isNullOrEmpty(scene)) {
            info.setCode(4);
            info.setMsg("参数错误");
            return info;
        }
        String[] scenes = scene.split("_");
        String rkey = Constants.REDIS_APP_USER + ObjectUtil.getMpid() + "_" + scenes[0];
        User ruser = userService.selectById(scenes[0]);
        if (ruser == null) {
            info.setCode(4);
            info.setMsg("商家用户不存在");
            return info;
        }

        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("请登录之后再操作");
            return info;
        }
        Long uid = null;
        try {
            uid = Long.parseLong(scenes[0]);
        } catch (Exception e) {
            info.setCode(1);
            info.setMsg("商家积分收款码非法");
            return info;
        }

        uid = ObjectUtil.getUid();
        boolean flag = false;
        JifenFlow jf = new JifenFlow();
        jf.setConfirmDate(new Date());
        jf.setCreatetime(new Date());
        jf.setIotype(IotypeEnum.output.getVal());
        jf.setIsConfirm(1);
        jf.setJftype(JftypeEnum.buy.getVal());
        jf.setMid(ObjectUtil.getMid());
        jf.setMpid(ObjectUtil.getMpid());
        jf.setRemark("用户积分支付给商家兑换商品服务");
        jf.setUid(uid);
        jf.setNum(jfcout);
        jf.setState(1);
        jf.setSn(StringUtil.getSnNo("J"));

        Jifen njifen;
        while (!flag) {

            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            njifen = new Jifen();

            long version = jifen.getVersion();
            njifen.setTotal(jf.getIotype() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
            njifen.setModifytime(new Date());
            njifen.setModifier(uid);
            njifen.setVersion(version + 1);

            flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
            if (flag) {
                jf.insert();
                // 返利推荐人【适用于恰恰全积分兑换平台】
                AkkaServer.system.actorOf(Props.create(FanliActor.class))
                        .tell(Constants.AKKA_FX_HEXIAO_OK + "@" + jf.getUid() + "@" + jfcout + "@" + XffanType.jifen.getVal(), ActorRef.noSender());
            }
        }

        // 积分转换到商家
        uid = Long.parseLong(scenes[0]);
        flag = false;

        jf.setId(null);
        jf.setIotype(IotypeEnum.input.getVal());
        jf.setJftype(JftypeEnum.sell.getVal());
        jf.setRemark("商家商品服务积分收款");
        jf.setUid(uid);

        while (!flag) {

            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            njifen = new Jifen();

            long version = jifen.getVersion();
            njifen.setTotal(jf.getIotype() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
            njifen.setModifytime(new Date());
            njifen.setModifier(uid);
            njifen.setVersion(version + 1);

            flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
            if (flag) {
                jf.insert();
                // 商家收款返利推荐人【适用于恰恰全积分兑换平台】
                AkkaServer.system.actorOf(Props.create(FanliActor.class))
                        .tell(Constants.AKKA_FX_HEXIAO_OK + "@" + uid + "@" + jfcout + "@" + XffanType.jifen.getVal(), ActorRef.noSender());
            }
        }
        return info;
    }

    @RequestMapping("/api/store/jfzhuanzeng")
    @ResponseBody
    public Jinfo jfzhuanzeng(String phone, BigDecimal jfcout) {
        Jinfo info = new Jinfo();

        if (Strings.isNullOrEmpty(phone)) {
            info.setCode(4);
            info.setMsg("参数错误");
            return info;
        }
        User user = userService.selectOne(new EntityWrapper<User>()
                .setSqlSelect("id,phone").eq("phone", phone)
                .eq("mpid", ObjectUtil.getMpid()));

        if (user == null) {
            info.setCode(4);
            info.setMsg("该手机号用户不存在");
            return info;
        }
        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("请登录之后再操作");
            return info;
        }

        Long uid = ObjectUtil.getUid();

        boolean flag = false;
        JifenFlow jf = new JifenFlow();
        jf.setConfirmDate(new Date());
        jf.setCreatetime(new Date());
        jf.setIotype(IotypeEnum.output.getVal());
        jf.setIsConfirm(1);
        jf.setJftype(JftypeEnum.gift.getVal());
        jf.setMid(ObjectUtil.getMid());
        jf.setMpid(ObjectUtil.getMpid());
        jf.setRemark("用户转赠积分给手机号为" + phone + "的用户");
        jf.setUid(uid);
        jf.setNum(jfcout);
        jf.setState(1);
        jf.setSn(StringUtil.getSnNo("J"));

        Jifen njifen;
        while (!flag) {

            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            njifen = new Jifen();

            long version = jifen.getVersion();
            njifen.setTotal(jf.getIotype() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
            njifen.setModifytime(new Date());
            njifen.setModifier(uid);
            njifen.setVersion(version + 1);

            flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
            if (flag) {
                jf.insert();
            }
        }

        // 积分转换到商家
        uid = user.getId();
        flag = false;

        jf.setId(null);
        jf.setIotype(IotypeEnum.input.getVal());
        jf.setJftype(JftypeEnum.gift.getVal());
        jf.setRemark(JftypeEnum.gift.getName());
        jf.setUid(uid);

        while (!flag) {

            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            njifen = new Jifen();

            long version = jifen.getVersion();
            njifen.setTotal(jf.getIotype() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
            njifen.setModifytime(new Date());
            njifen.setModifier(uid);
            njifen.setVersion(version + 1);

            flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
            if (flag) {
                jf.insert();
            }
        }

        return info;
    }


    //营销版商家概况中心
    @RequestMapping("/api/store/center")
    @ResponseBody
    public Jinfo scenter() {

        Jinfo json = new Jinfo();
        Long sid = ObjectUtil.getSid();
        if (sid == null || sid == 0) {
            json.setCode(1);
            json.setMsg("没有权限查看商家概况");
            return json;
        }
        Store store = storeService.selectById(sid);
        if (sid == null || sid == 0) {
            json.setCode(1);
            json.setMsg("商家不存在");
            return json;
        }
        User muser = userService.selectOne(new EntityWrapper<User>()
                .eq("is_mch", 1).eq("is_admin", 1).eq("sid", sid));
        if (muser == null) {
            json.setCode(1);
            json.setMsg("商家管理员不存在");
            return json;
        }
        Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", muser.getId()));
        if (account == null) {
            json.setCode(1);
            json.setMsg("商家资金账户不存在");
            return json;
        }
        StoreStat storeStat = storeStatMapper.selectById(sid);
        storeStat.setKeyong(account.getAmount());
        storeStat.setDairuzhang(account.getFanliing());

        json.setInfo(storeStat);

        return json;
    }

    //营销版商家活动订单《商家端》
    /*
     * @描述营销版商家活动订单
     * @param pageIndex:第几页
     * @param pageSize:页大小
     * @param phone:搜索手机号(选填)
     * @param gid:搜索活动id(选填)
     * @out id,linkman,phone,headimg,status,type
     */
    @RequestMapping("/api/store/hdorders")
    @ResponseBody
    public Jinfo hdorders(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                          @RequestParam(value = "pageSize", required = false) Integer pageSize,
                          @RequestParam(value = "phone", required = false) String phone,
                          @RequestParam(value = "statday", required = false) String statday,
                          @RequestParam(value = "status", required = false) Integer status,
                          @RequestParam(value = "gid", required = false) Long gid
    ) {

        Jinfo json = new Jinfo();
        Long sid = ObjectUtil.getSid();
        if (sid == null || sid == 0) {
            json.setCode(1);
            json.setMsg("没有权限查看商家概况");
            return json;
        }
        User user = redisService.getUser();
        Store store = storeService.selectById(sid);
        if (user.getIsPlatform() != 1 && (store == null || sid == 0)) {
            json.setCode(1);
            json.setMsg("商家不存在");
            return json;
        }

        User muser = userService.selectOne(new EntityWrapper<User>()
                .eq("is_mch", 1).eq("is_admin", 1).eq("sid", sid));

        if (user.getIsPlatform() != 1 && muser == null) {
            json.setCode(1);
            json.setMsg("商家管理员不存在");
            return json;
        }
        pageIndex = pageIndex == null ? 1 : pageIndex;
        pageSize = pageSize == null ? 20 : pageSize;
        logger.info("--------------------------------------pageIndex=" + pageIndex);
        logger.info("--------------------------------------pageSize=" + pageSize);
        Page<Order> page = new Page<Order>(pageIndex, pageSize);

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .setSqlSelect("id,gid,linkman,phone,realpay,total,headimg,status,type,gtype,address,fhstate,spec,minprice,sharefan,ptfan," +
                        "shipper_method shipperMethod,shipper_name shipperName,is_refund isRefund,yundanno,pic," +
                        "goods_name goodsName,goods_number goodsNumber," +
                        "paytime,yytime,jdtime,fhtime,confirmtime");
        if (!Strings.isNullOrEmpty(phone)) {
            entity.eq("phone", phone);
        }
        if (!Strings.isNullOrEmpty(statday)) {
            entity.like("order_no", statday.replaceAll("-", ""));
        }
        if (gid != null && gid.doubleValue() > 0) {
            entity.eq("gid", gid);
        }
        if (status != null && status == 1) {
            entity.eq("status", status);
        } else if (status != null && status == 2) {
            entity.ge("status", status);
        }
        if (user.getIsPlatform() != 1 && sid != null) {
            entity.eq("sid", sid);
        }
        entity.orderBy("id", false);
        Page<Order> plist = orderService.selectPage(page, entity);

        json.setInfo(plist.getRecords());

        return json;
    }

    //营销版商家活动+商品列表
    /*
     * @描述营销版商家活动列表
     * @out id,name
     */
    @RequestMapping("/api/store/hdgoods")
    @ResponseBody
    public Jinfo hdgoodsList() {

        Jinfo json = new Jinfo();
        Long sid = ObjectUtil.getSid();
        if (sid == null || sid == 0) {
            json.setCode(1);
            json.setMsg("没有权限查看商家概况");
            return json;
        }
        List<Goods> list = new ArrayList<Goods>();
        Goods g = new Goods();
        g.setName("所有活动商品");
        list.add(g);

        Wrapper<Goods> entity = new EntityWrapper<Goods>()
                .setSqlSelect("id,name")
                .eq("sid", sid).eq("is_deleted", -1)
                .orderBy("id", false);

        list.addAll(goodsService.selectList(entity));

        json.setInfo(list);
        return json;
    }

    //营销版商家活动+商品列表<联盟端>
    /*
     * @描述营销版商家活动列表
     * @out id,name
     */
    @RequestMapping("/api/agent/hdgoods")
    @ResponseBody
    public Jinfo lmgoodsList() {

        Jinfo json = new Jinfo();
        Long leagueid = redisService.getLeagueid();
        if (leagueid == null || leagueid == 0) {
            json.setCode(1);
            json.setMsg("无权限查看联盟商家活动概况");
            return json;
        }

        List<Goods> list = new ArrayList<Goods>();
        Goods g = new Goods();
        g.setName("所有活动商品");
        list.add(g);

        Wrapper<Goods> entity = new EntityWrapper<Goods>()
                .setSqlSelect("id,name")
                .eq("leagueid", leagueid).eq("is_deleted", -1)
                .orderBy("id", false);

        list.addAll(goodsService.selectList(entity));

        json.setInfo(list);
        return json;
    }

    @RequestMapping("/api/merchant/center")
    @ResponseBody
    public Jinfo mcenter() {

        Jinfo json = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Long mid = ObjectUtil.getMid();
        Long uid = ObjectUtil.getUid();

        Maccount maccount = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));

        int daifu = orderService.selectCount(new EntityWrapper<Order>()
                .eq("mpid", mpid).eq("status", 1));

        int daifa = orderService.selectCount(new EntityWrapper<Order>()
                .eq("mpid", mpid).eq("status", 2));

        int dingdanshu = orderService.selectCount(new EntityWrapper<Order>()
                .eq("mpid", mpid).ge("status", 2));

        Order allOrder = orderService.selectOne(new EntityWrapper<Order>()
                .setSqlSelect("sum(realpay) realpay")
                .eq("mpid", mpid).ge("status", 2));

        Wrapper<Order> wrapper = new EntityWrapper<Order>().setSqlSelect("id,realpay")
                .where("mpid={0} and status>=2 and date(createtime)=date(now()) and is_refund=-1", mpid);
        List<Order> tlist = orderService.selectList(wrapper);

        BigDecimal money = new BigDecimal(0);
        for (Order order : tlist) {
            money.add(order.getRealpay());
        }

        int todayOrders = tlist == null ? 0 : tlist.size();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("lsxiaoshou", maccount.getSaleAmount());//总销售额
        map.put("zdingdanshu", dingdanshu);//订单总数
        map.put("zdingdane", allOrder == null ? 0 : allOrder.getRealpay());//订单额

        map.put("daifu", daifu);
        map.put("daifa", daifa);
        map.put("money", money);
        map.put("todayOrders", todayOrders);
        json.setInfo(map);

        return json;
    }

    @RequestMapping("/api/merchant/sjcenter")
    @ResponseBody
    public Jinfo sjcenter() {

        Jinfo json = new Jinfo();
        Long sid = ObjectUtil.getSid();
        if (sid == null || sid == 0) {
            json.setCode(1);
            json.setMsg("没有权限查看商家概况");
            return json;
        }
        Store store = storeService.selectById(sid);
        if (sid == null || sid == 0) {
            json.setCode(1);
            json.setMsg("商家不存在");
            return json;
        }
        User muser = userService.selectOne(new EntityWrapper<User>()
                .eq("is_mch", 1).eq("is_admin", 1).eq("sid", sid));
        if (muser == null) {
            json.setCode(1);
            json.setMsg("商家管理员不存在");
            return json;
        }
        Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", muser.getId()));
        if (account == null) {
            json.setCode(1);
            json.setMsg("商家资金账户不存在");
            return json;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("views", store.getViews());
        map.put("storename", store.getName());
        map.put("storepic", store.getThumb());
        map.put("dairuzhang", account.getFanliing());
        map.put("keyong", account.getAmount());

        int dingdanshu = orderService.selectCount(new EntityWrapper<Order>().where("sid=" + sid + " and status>1"));

        int huodongshu = goodsService.selectCount(new EntityWrapper<Goods>()
                .where("sid=" + sid + " and type>0 and is_deleted=-1"));//营销活动type > 0
//                .where("sid=" + sid + " and type>0 and DATE_FORMAT(createtime,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m')"));

        String month = DateUtil.toDateString("YYYYMM");
        Double money = orderService.getOrderMoneyCountbyMonth(sid, month);

        map.put("dingdanshu", dingdanshu);
        map.put("huodongshu", huodongshu);
        map.put("canyushu", dingdanshu);
        map.put("money", money == null ? 0 : money);

        json.setInfo(map);

        return json;
    }

    //商家设置分销功能接口
    //@param state 是否开启@1：开启；-1：禁用
    //@param payshare 分销佣金比例
    //@param fangshua 是否开启防刷@1：开启；-1：禁用
    @RequestMapping("/api/store/setmdpay")
    @ResponseBody
    public Jinfo setmdpay(
            @RequestParam(value = "state", required = false) Integer state,
            @RequestParam(value = "payshare", required = false) Integer payshare,
            @RequestParam(value = "fangshua", required = false) Integer fangshua
    ) {

        Jinfo info = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        Long sid = ObjectUtil.getSid();

        if (sid == null || sid <= 0l) {
            info.setCode(1);
            info.setMsg("非商家不能进行该操作");
            return info;
        }
        if (payshare <= 0 || payshare >= 100) {
            info.setCode(1);
            info.setMsg("分销比例设置有误");
            return info;
        }

        Mdpay mdpay = mdpayMapper.selectById(sid);
        BigDecimal one = new BigDecimal(1);
        BigDecimal ten = new BigDecimal(0.1);
        if (mdpay == null) {
            mdpay.setSid(sid);
            mdpay.setMpid(mpid);
            mdpay.setPaymeng(ten);
            mdpay.setPayplat(ten);

            mdpay.setPayshare(new BigDecimal(payshare).divide(new BigDecimal(100)));
            mdpay.setState(state);
            mdpay.setFangshua(fangshua);
            mdpay.setPaymch(one.subtract(mdpay.getPayplat()).subtract(mdpay.getPaymeng()).subtract(mdpay.getPayshare()));

            mdpay.setCreatetime(new Date());
            mdpay.setLeagueid(redisService.getLeagueid(sid));

        } else {
            mdpay.setPayshare(new BigDecimal(payshare).divide(new BigDecimal(100)));
            mdpay.setState(state);
            mdpay.setFangshua(fangshua);
            mdpay.setPaymch(one.subtract(mdpay.getPayplat()).subtract(mdpay.getPaymeng()).subtract(mdpay.getPayshare()));
            mdpay.setModifytime(new Date());
        }

        mdpay.insertOrUpdate();
        return info;
    }

    //获取商家设置分销
    @RequestMapping("/api/store/getmdpay")
    @ResponseBody
    public Jinfo getmdpay() {

        Jinfo info = new Jinfo();
        User ruser = redisService.getUser();
        Long lmid = redisService.getLeagueid();

        Long sid = ObjectUtil.getSid();
        if (lmid == null && (sid == null || sid <= 0l)) {
            info.setCode(1);
            info.setMsg("非商家或管理员不能进行该操作");
            return info;
        }
        if (sid == null) {
            Wrapper<Store> entity = new EntityWrapper<Store>();
            entity.setSqlSelect("id,name,phone,wxno").eq("state", 1)
                    .eq("leagueid", lmid);
            List<Store> list = storeService.selectList(entity);
            if (list != null && list.size() > 0) sid = list.get(0).getId();
        }

        Mdpay mdpay = mdpayMapper.selectById(sid);
        if (mdpay == null) {
            mdpay = new Mdpay();
            mdpay.setSid(sid);
            mdpay.setMpid(ObjectUtil.getMpid());
            mdpay.setCreatetime(new Date());

            mdpay.setState(1);
            mdpay.setFangshua(-1);
            mdpay.setLeagueid(redisService.getLeagueid(sid));

            mdpay.setPaymch(new BigDecimal(0.7));//商家默认0.7
            mdpay.setPayplat(new BigDecimal(0.1));//平台默认0.1
            mdpay.setPayshare(new BigDecimal(0.1));//分享者默认0.1
            mdpay.setPaymeng(new BigDecimal(0.1));//默认0.1
            mdpay.insert();
        }

        info.setInfo(mdpay);
        return info;
    }

    //获取商家活动克隆商家列表
    @RequestMapping("/api/store/getCloneMchs")
    @ResponseBody
    public Jinfo getCloneMchs(@RequestParam(value = "sid", required = false) Long sid) {

        Jinfo info = new Jinfo();

        Wrapper<Store> entity = new EntityWrapper<Store>();
        entity.setSqlSelect("id,name,phone,wxno").eq("state", 1)
                .eq("mpid", ObjectUtil.getMpid());

        User user = redisService.getUser();
        if (user.getIsPlatform() == 1) {

        } else if (user.getIsAgent() == 1) {

            League league = leagueMapper.selectById(user.getLeagueid());
            if (league == null) {
                info.setCode(1);
                info.setMsg("参数有误");
                return info;
            }
            entity.eq("leagueid", league.getId());

        } else if (user.getIsMch() == 1) {
            Long msid = ObjectUtil.getSid();
            if (msid == null) {
                info.setCode(1);
                info.setMsg("无权限访问");
                return info;
            }
            entity.eq("id", msid);
        } else {
            info.setCode(1);
            info.setMsg("无权限访问");
            return info;
        }
        if (sid != null) entity.eq("id", sid);
        List<Store> list = storeService.selectList(entity);
        info.setInfo(list);
        String startday = DateUtil.getNowTime("yyyy-MM-dd HH:mm");
        String endday = DateUtil.addToday(3, "yyyy-MM-dd HH:mm");
        JSONObject jo = new JSONObject();
        jo.put("startday", startday);
        jo.put("endday", endday);
        info.setExtra(jo);

        return info;
    }

    //获取商家财务概况
    @RequestMapping("/api/store/caiwugk")
    @ResponseBody
    public Jinfo caiwugk() {

        Jinfo info = new Jinfo();

        Wrapper<Store> entity = new EntityWrapper<Store>();
        entity.setSqlSelect("id,name").eq("state", 1)
                .eq("mpid", ObjectUtil.getMpid());

        User user = redisService.getUser();
        if (user.getIsPlatform() == 1) {

        } else if (user.getIsAgent() == 1) {
            League leaguety = new League();
            leaguety.setUid(ObjectUtil.getUid());
            leaguety.setMpid(ObjectUtil.getMpid());
            League league = leagueMapper.selectOne(leaguety);
            if (league == null) {
                info.setCode(1);
                info.setMsg("参数有误");
                return info;
            }
            entity.eq("leagueid", league.getId());

        } else if (user.getIsMch() == 1) {
            Long msid = ObjectUtil.getSid();
            if (msid == null) {
                info.setCode(1);
                info.setMsg("无权限访问");
                return info;
            }
            entity.eq("id", msid);
        } else {
            info.setCode(1);
            info.setMsg("无权限访问");
            return info;
        }
        List<Store> list = storeService.selectList(entity);
        info.setInfo(list);

        return info;
    }


    //营销版商家活动订单《联盟端》
    /*
     * @描述营销版商家活动订单
     * @param pageIndex:第几页
     * @param pageSize:页大小
     * @param phone:搜索手机号(选填)
     * @param gid:搜索活动id(选填)
     * @out id,linkman,phone,headimg,status,type
     */
    @RequestMapping("/api/agent/hdorders")
    @ResponseBody
    public Jinfo agenthdorders(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                               @RequestParam(value = "pageSize", required = false) Integer pageSize,
                               @RequestParam(value = "phone", required = false) String phone,
                               @RequestParam(value = "statday", required = false) String statday,
                               @RequestParam(value = "gid", required = false) Long gid
    ) {

        Jinfo json = new Jinfo();
        Long leagueid = redisService.getLeagueid();
        if (leagueid == null || leagueid == 0) {
            json.setCode(1);
            json.setMsg("没有权限查看联盟商家订单概况");
            return json;
        }

        pageIndex = pageIndex == null ? 1 : pageIndex;
        pageSize = pageSize == null ? 20 : pageIndex;
        Page<Order> page = new Page<Order>(pageIndex, pageSize);

        Wrapper<Order> entity = new EntityWrapper<Order>()
                .setSqlSelect("id,gid,linkman,phone,realpay,total,headimg,status,type,gtype,address,fhstate,spec,minprice,sharefan,ptfan," +
                        "shipper_method shipperMethod,shipper_name shipperName,is_refund isRefund,yundanno,pic," +
                        "goods_name goodsName,goods_number goodsNumber," +
                        "paytime,yytime,jdtime,fhtime,confirmtime")
                .eq("leagueid", leagueid);
        if (!Strings.isNullOrEmpty(phone)) {
            entity.eq("phone", phone);
        }
        if (!Strings.isNullOrEmpty(statday)) {
            entity.like("order_no", statday.replaceAll("-", ""));
        }
        if (gid != null && gid.doubleValue() > 0) {
            entity.eq("gid", gid);
        }
        entity.orderBy("id", false);
        Page<Order> plist = orderService.selectPage(page, entity);

        json.setInfo(plist.getRecords());

        return json;
    }

    //营销版商家活动订单《商家端》
    /*
     * @描述营销版商家活动订单
     * @param pageIndex:第几页
     * @param pageSize:页大小
     * @param phone:搜索手机号(选填)
     * @param gid:搜索活动id(选填)
     * @out id,linkman,phone,headimg,status,type
     */
    @RequestMapping("/api/store/dphuiyuan")
    @ResponseBody
    public Jinfo dphuiyuan(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                           @RequestParam(value = "pageSize", required = false) Integer pageSize,
                           @RequestParam(value = "isleague", required = false) Integer isleague,
                           @RequestParam(value = "phone", required = false) String phone) {

        Jinfo json = new Jinfo();

        User user = redisService.getUser();
        Long leagueid = redisService.getLeagueid();
        Long sid = ObjectUtil.getSid();
        if (user == null || (user.getIsPlatform() != 1 && user.getIsAgent() != 1 && sid == null)) {
            return json;
        }

        pageIndex = pageIndex == null ? 1 : pageIndex;
        pageSize = pageSize == null ? 20 : pageIndex;
        Page<LeagueMember> page = new Page<LeagueMember>(pageIndex, pageSize);

        Wrapper<LeagueMember> entity = new EntityWrapper<LeagueMember>()
                .eq("mpid", ObjectUtil.getMpid());
        if (isleague != null && isleague == 1 && leagueid != null) {
            entity.setSqlSelect("uid,sid,phone,nickname,headimg,startdate,enddate,state,sname,mlevel,utype");
            entity.eq("leagueid", leagueid);
        } else if (sid != null && sid > 0) {
            entity.setSqlSelect("uid,sid,phone,nickname,headimg,startdate,enddate,state,sname,mlevel,utype");
            entity.eq("sid", sid);
        }

        if (!Strings.isNullOrEmpty(phone)) {
            entity.eq("phone", phone);
        }
        entity.orderBy("id", false);
        Page<LeagueMember> plist = leagueMemberService.selectPage(page, entity);

        List<LeagueMember> list = plist.getRecords();
        for (LeagueMember item : list) {
            item.setFens(leagueMemberService.selectCount(new EntityWrapper<LeagueMember>().eq("shareid", item.getUid()).eq("sid", item.getSid())));
            item.setFens2(leagueMemberService.selectCount(new EntityWrapper<LeagueMember>().eq("pshareid", item.getUid()).eq("sid", item.getSid())));
            if (Strings.isNullOrEmpty(item.getEndday())) continue;
            item.setEndday(item.getEndday().replaceAll("-", ""));
        }
        json.setInfo(list);
        return json;
    }

    //联盟版商家会员信息《用户端》
    /*
     * @店铺会员
     * @param pageIndex:第几页
     */
    @RequestMapping("/api/store/memberinfo")
    @ResponseBody
    public Jinfo memberinfo(Long sid) {

        Jinfo info = new Jinfo();
        if (sid == null) sid = ObjectUtil.getSid();
        if (sid == null) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }
        if (ObjectUtil.getUid() == null) {
            info.setCode(1);
            info.setMsg("请授权登录之后再访问");
            return info;
        }
        Long uid = ObjectUtil.getUid();
        Wrapper<LeagueMember> entity = new EntityWrapper<LeagueMember>()
                .eq("uid", uid).eq("sid", sid);
        LeagueMember leagueMember = leagueMemberService.selectOne(entity);

//        if (leagueMember == null) {
//            info.setCode(1);
//            info.setMsg("当前用户非商家会员");
//            return info;
//        }

        //大于等于1级
        List<CoupontplMember> coupontplMembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
                .eq("sid", sid).ge("mlevel", 1).orderBy("mlevel"));
        if (coupontplMembers == null) {
            info.setCode(1);
            info.setMsg("当前商家裂变会员未设置");
            return info;
        }

        int level = 1;
        String mquanyi = "";
        List<CoupontplMember> smembers = new ArrayList<CoupontplMember>();
        Store store = storeService.selectOne(new EntityWrapper<Store>()
                .setSqlSelect("id,name,thumb,phone,wxno").eq("id", sid));

        //
        for (int i = 0; i < coupontplMembers.size(); i++) {
            level = coupontplMembers.get(i).getMlevel().intValue();
            if (level <= smembers.size()) {
                smembers.get(level - 1).getMms().add(coupontplMembers.get(i));
            } else {
                CoupontplMember mm = new CoupontplMember();
                mm.setMlevel(level);
                mm.getMms().add(coupontplMembers.get(i));
                smembers.add(mm);
            }
            if (leagueMember != null && level == leagueMember.getMlevel()) {
                mquanyi += coupontplMembers.get(i).getMquanyi() + "+";
            }
        }
        if (mquanyi != null && mquanyi.endsWith("+")) mquanyi = mquanyi.substring(0, mquanyi.length() - 1);
        if (leagueMember != null && mquanyi == null) {
            mquanyi = "一个月体验会员";
        }
        if (leagueMember == null) leagueMember = new LeagueMember();
        leagueMember.setMquanyi(mquanyi);
        leagueMember.setStore(store);

        //查询3张未使用券
        Page<Coupon> page = new Page<Coupon>(1, 3);
        Page<Coupon> quans = couponService.selectPage(page, new EntityWrapper<Coupon>()
                .eq("uid", uid).eq("state", 1).eq("is_unused", 1).eq("sid", sid));

        //推荐的人在该商家使用消费多少券
        int xiaofei = couponService.selectCount(new EntityWrapper<Coupon>().eq("zfuid", uid)
                .eq("sid", sid)
                .eq("is_used", 1));

        List<Coupon> xfuser = couponService.selectList(new EntityWrapper<Coupon>()
                .setSqlSelect("distinct uid").eq("sid", sid)
                .eq("zfuid", uid));
        Map<String, Integer> map = new HashMap<String, Integer>();
        //分享多少用户
        map.put("yonghu", xfuser.size());
        //累计用券消费
        map.put("xiaofei", xiaofei);
        //查询是否是商家会员
        User user = redisService.getUser();
        map.put("isMch", user.getIsMch());

        info.setInfo(smembers);
        info.setExtra(leagueMember);
        info.setData(quans.getRecords());
        info.setMap(map);
        return info;
    }

    //联盟版商家会员信息《用户端》
    /*
     * @店铺会员
     * @param pageIndex:第几页
     */
    @RequestMapping("/api/store/annomemberinfo")
    @ResponseBody
    public Jinfo annomemberinfo(Long sid) {

        Jinfo info = new Jinfo();
        if (sid == null) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }

        LeagueMember leagueMember = new LeagueMember();

        //大于等于1级
        List<CoupontplMember> coupontplMembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
                .eq("sid", sid).ge("mlevel", 1).orderBy("mlevel"));
        if (coupontplMembers == null) {
            info.setCode(1);
            info.setMsg("当前商家裂变会员未设置");
            return info;
        }

        int level = 1;
        String mquanyi = "";
        List<CoupontplMember> smembers = new ArrayList<CoupontplMember>();
        Store store = storeService.selectOne(new EntityWrapper<Store>()
                .setSqlSelect("id,name,thumb,phone,wxno").eq("id", sid));

        for (int i = 0; i < coupontplMembers.size(); i++) {
            level = coupontplMembers.get(i).getMlevel().intValue();
            if (level <= smembers.size()) {
                smembers.get(level - 1).getMms().add(coupontplMembers.get(i));
            } else {
                CoupontplMember mm = new CoupontplMember();
                mm.setMlevel(level);
                mm.getMms().add(coupontplMembers.get(i));
                smembers.add(mm);
            }
            if (level == coupontplMembers.get(i).getMlevel()) {
                mquanyi += coupontplMembers.get(i).getMquanyi() + "+";
            }
        }
        if (mquanyi != null && mquanyi.endsWith("+")) mquanyi = mquanyi.substring(0, mquanyi.length() - 1);

        leagueMember.setMquanyi(mquanyi);
        leagueMember.setStore(store);

        info.setInfo(smembers);
        info.setExtra(leagueMember);
        return info;
    }

    @RequestMapping("/api/store/setting")
    @ResponseBody
    public Jinfo setting(@RequestParam(value = "v", required = false) Integer version
            , @RequestParam(value = "sid", required = false) Long sid
            , @RequestParam(value = "isadmin", required = false) Integer isadmin
            , @RequestParam(value = "type", required = false) String type
            , @RequestParam(value = "extra", required = false) String extra
            , @RequestParam(value = "buy", required = false) Integer buy
            , @RequestParam(value = "mchpstype", required = false) Integer mchpstype
            , @RequestParam(value = "gtype", required = false) Integer gtype) {

        Jinfo json = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        if (sid == null) sid = ObjectUtil.getSid();
        if (sid == null) {
            json.setCode(1);
            json.setMsg("无权限访问");
            return json;
        }
        Store store = redisService.getStore(sid);
        if (store == null) {
            json.setCode(1);
            json.setMsg("该商家不存在");
            return json;
        }

        //返回快递类型
        if (store.getPstype() != null && (store.getPstype() == 1 || store.getPstype() == 2)) {
            //获取快递公司
            List<Config> kuaidi = configService.selectList(new EntityWrapper<Config>().setSqlSelect("name,code")
                    .eq("sid", sid)
                    .eq("pcode", "kuaidibianma").orderBy("sort"));
            json.setData(kuaidi);
        }

        json.setInfo(store);
        return json;
    }

    //视频页面拨打电话记录
    @RequestMapping("/api/store/calllog")
    @ResponseBody
    public Jinfo calllog(@RequestParam(value = "sid", required = false) Long sid,
                         @RequestParam(value = "ywid", required = false) Long ywid) {

        Jinfo json = new Jinfo();
        News news = newsService.selectById(ywid);
        if (news != null) {
            news.setZixuncout(news.getZixuncout() == null ? 1 : news.getZixuncout() + 1);
            news.setModifytime(new Date());
            news.updateById();
        }

        return json;
    }

    @RequestMapping("/api/store/buyinfo")
    @ResponseBody
    public Jinfo storebuyinfo(@RequestParam(value = "sid", required = false) Long sid,
                              @RequestParam(value = "gid", required = false) Long gid) {
        Jinfo info = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Wrapper<Store> entity = new EntityWrapper<Store>()
                .setSqlSelect("id,address,characteristic,name,zhizhao,info,pstype,peisongfee,video,is_liansuo isLiansuo,is_parking isParking,is_waimai isWaimai,is_wifi isWifi," +
                        "is_tihuo isTihuo,is_yikatong isYikatong,is_dulizs isDulizs,is_cbct isCbct,pingfen,xuzhi,sellnum,logo,renqi,views,xiangqing," +
                        "is_wxpay isWxpay,is_zfbpay isZfbpay,is_auth isAuth,latitude,linkman,longitude,open_hour openHour,phone,phone2,photos,pic,pjprice,price,type,zhutui,xukezheng")
                .eq("mpid", mpid);

        if (sid != null && sid > 0) entity.eq("id", sid);
        Store store = storeService.selectOne(entity);
        if (store == null) return info;

        info.setInfo(store);

        if (gid != null) {
            Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().setSqlSelect("id,pstype").eq("id", gid));
            info.setExtra(goods == null ? "" : goods.getPstype());
        }
        return info;
    }

    //视频页面拨打电话记录
    @RequestMapping("/api/store/qrimg")
    @ResponseBody
    public Jinfo storeQrimg(@RequestParam(value = "sid", required = true) Long sid) {

        Jinfo json = new Jinfo();
        MerchantApp mapp = redisService.getMApp();
        String path = Constants.WX_MQR_PATH.replace("MCODE", mapp.getMcode()).replace("MPCODE", mapp.getMpcode());
        HttpUtil.checkDirectory(path);
        path = path + "_storeqr_" + sid + ".png";
        // scene format //uid+page+act+ywid
        String scene = "322_mdetail_Q_" + sid;
        // 统一用无限制带参二维码
        String page = "pages/mdetail/mdetail?sid=" + sid;
        logger.debug("========================================api/user/info page=" + page);
        logger.debug("========================================api/user/info scene=" + scene);
        String qr = HttpUtil.getminiQr(redisService.getWxtoken(), path, page, scene, 400, true, "", false);
        logger.debug("==========qr=" + qr);
        json.setInfo(qr);

        return json;
    }


    //收藏
    @RequestMapping("/api/store/addfavor")
    @ResponseBody
    public Jinfo addfavor(@RequestParam(value = "sid", required = true) Long sid) {

        Jinfo json = new Jinfo();
        if (ObjectUtil.getUid() == null) {
            json.setCode(1);
            json.setMsg("无权限访问");
            return json;
        }
        StoreFavor entity = new StoreFavor();
        entity.setSid(sid);
        entity.setUid(ObjectUtil.getUid());
        StoreFavor storeFavor = storeFavorMapper.selectOne(entity);
        if (storeFavor != null) {
            json.setCode(1);
            json.setMsg("已收藏过该店铺");
            return json;
        }
        storeFavor = new StoreFavor();
        storeFavor.setSid(sid);
        storeFavor.setUid(ObjectUtil.getUid());
        storeFavor.insert();

        return json;
    }

    @RequestMapping("/api/store/favor/list")
    @ResponseBody
    public Jinfo getNearbyFavorStores(HttpServletRequest req, @RequestParam(value = "sid", required = false) String sou) {
        Jinfo info = new Jinfo();

        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        if (uid == null) {
            info.setCode(1);
            info.setMsg("请先登录后再查询我的收藏");
            return info;
        }
        List<Store> list = storeService.getNearbyFavorStores(mpid, uid, sou);
        for (Store item : list) {
            item.setShoucang(1);
        }
        info.setInfo(list);
        return info;
    }


    //收藏
    @RequestMapping("/api/store/cancelfavor")
    @ResponseBody
    public Jinfo cancelfavor(@RequestParam(value = "sid", required = true) Long sid) {

        Jinfo json = new Jinfo();
        if (ObjectUtil.getUid() == null) {
            json.setCode(1);
            json.setMsg("无权限访问");
            return json;
        }
        StoreFavor entity = new StoreFavor();
        entity.setSid(sid);
        entity.setUid(ObjectUtil.getUid());
        storeFavorMapper.delete(new EntityWrapper<StoreFavor>().eq("sid", sid).eq("uid", ObjectUtil.getUid()));

        return json;
    }

    @RequestMapping("/api/store/setlevel")
    @ResponseBody
    public Jinfo setlevel(@RequestParam(value = "sid") Long sid, @RequestParam(value = "melvel") Integer melvel) {
        Jinfo info = new Jinfo();
        Store store = storeService.selectById(sid);
        if (store == null) {
            info.setCode(4);
            info.setMsg("商家信息不存在");
            return info;
        }

        if (melvel == null || (melvel < 0 || melvel > 2)) {
            info.setCode(1);
            info.setMsg("参数非法");
            return info;
        }

        Store ustore = new Store();
        ustore.setId(sid);
        ustore.setMlevel(melvel);
        ustore.setModifier(ObjectUtil.getUid());
        ustore.setModifytime(new Date());
        ustore.updateById();

        //复制永利口腔的会员券
        List<CouponTpl> quans = couponTplService.selectList(new EntityWrapper<CouponTpl>()
                .eq("sid", sid)
                .eq("type", 4).orderBy("mlevel"));
        if(quans==null||quans.size()==0){
            List<CouponTpl> ylquans = couponTplService.selectList(new EntityWrapper<CouponTpl>()
                    .eq("sid", "2493")
                    .eq("type", 4).orderBy("mlevel"));
            for(CouponTpl tpl:ylquans){
                tpl.setId(null);
                tpl.setSname(store.getName());
                tpl.setSid(store.getId());
                tpl.setSlogo(store.getLogo());
                tpl.setModifytime(new Date());
                tpl.setModifier(ObjectUtil.getUid());
                tpl.insert();
            }
        }

        return info;
    }

    //华口云专用---领取会员
    @RequestMapping("/api/store/setMemberInfo")
    @ResponseBody
    public Jinfo setMemberInfo(@RequestParam(value = "sid") Long sid,
                               @RequestParam(value = "name") String name,
                               @RequestParam(value = "ori", required = false) String ori,
                               @RequestParam(value = "phone") String phone) {

        Jinfo info = new Jinfo();
        Store store = storeService.selectById(sid);
        if (store == null) {
            info.setCode(4);
            info.setMsg("商家信息不存在");
            return info;
        }
        if (ObjectUtil.getUid() == null) {
            info.setCode(4);
            info.setMsg("用户未登录");
            return info;
        }

        if (Strings.isNullOrEmpty(name) || Strings.isNullOrEmpty(phone)) {
            info.setCode(1);
            info.setMsg("参数非法");
            return info;
        }
        User user = new User();
        user.setId(ObjectUtil.getUid());
        user.setName(name);
        user.setName(phone);
        user.setModifytime(new Date());
        user.setModifier(ObjectUtil.getUid());

        user.updateById();
        user = userService.selectById(ObjectUtil.getUid());

        Fens fens = fensService.selectOne(new EntityWrapper<Fens>().eq("uid", ObjectUtil.getUid()).eq("level_type", 1));

        //生成店铺会员信息
        LeagueMember leagueMember = new LeagueMember();
        leagueMember.setSid(sid);
        leagueMember.setNickname(name);
        leagueMember.setSname(store.getName());
        leagueMember.setPhone(phone);
        leagueMember.setUid(ObjectUtil.getUid());
        leagueMember.setHeadimg(user.getAvatarPic());
        leagueMember.setCreatetime(new Date());
        leagueMember.setCreateday(DateUtil.getToday());
        leagueMember.setMid(ObjectUtil.getMid());
        leagueMember.setMpid(ObjectUtil.getMpid());
        leagueMember.setMlevel(1);
        if (!Strings.isNullOrEmpty(ori)) {
            String guid = ori.substring(0, ori.indexOf("_"));
            logger.debug("========================================setMemberInfo guid=" + guid);
            User oriuser = userService.selectOne(new EntityWrapper<User>().eq("guid", guid));
            if (oriuser != null) leagueMember.setShareid(oriuser.getId());
        } else if (fens != null) {
            leagueMember.setShareid(fens.getPuid());
        }
        leagueMember.insert();

        if (leagueMember.getShareid() != null) {
            LeagueMember shareLeagueMember = leagueMemberService.selectOne(new EntityWrapper<LeagueMember>().eq("uid", leagueMember.getShareid()).eq("sid", sid));
            int shareCout = leagueMemberMapper.selectCount(new EntityWrapper<LeagueMember>().eq("shareid", leagueMember.getShareid()).eq("sid", sid));

            List<CouponTpl> quans = couponTplService.selectList(new EntityWrapper<CouponTpl>()
                    .eq("sid", sid)
                    .eq("type", 4).orderBy("mlevel"));
            boolean updateMlevel = false;
            for (CouponTpl tpl : quans) {
                if (tpl.getShareshu() == null) continue;
                if (shareCout >= tpl.getShareshu()) {
                    shareLeagueMember.setMlevel(tpl.getMlevel());
                    updateMlevel = true;
                }
            }
            if(updateMlevel) {
                shareLeagueMember.setModifytime(new Date());
                shareLeagueMember.setModifior(ObjectUtil.getUid());
                shareLeagueMember.updateById();
            }
        }

        return info;
    }


    //华口云专用---会员升级详情页面
    @RequestMapping("/api/store/hkmemberInfo")
    @ResponseBody
    public Jinfo hkmemberInfo(@RequestParam(value = "sid") Long sid) {

        Jinfo info = new Jinfo();
        Store store = storeService.selectById(sid);
        Long uid = ObjectUtil.getUid();
        if (store == null) {
            info.setCode(4);
            info.setMsg("商家信息不存在");
            return info;
        }
        if (uid == null) {
            info.setCode(4);
            info.setMsg("用户未登录");
            return info;
        }

        //推广的会员
        List<LeagueMember> fens = leagueMemberMapper.selectList(new EntityWrapper<LeagueMember>().eq("shareid", uid).eq("sid", sid));
        info.setData(fens);

        //获取四个券
        List<CouponTpl> quans = couponTplService.selectList(new EntityWrapper<CouponTpl>()
                .eq("sid", sid)
                .eq("type", 4).orderBy("mlevel"));

        for (CouponTpl tpl : quans) {
            Coupon coupon = couponService.selectOne(new EntityWrapper<Coupon>().eq("uid", uid).eq("tplid", tpl.getId()));
            if (coupon != null) {
                tpl.setCno(coupon.getCno());
                tpl.setCouponId(coupon.getId());
                tpl.setTplid(tpl.getId());
                tpl.setState(1);
                tpl.setUsed(coupon.getIsUsed());
            } else {
                tpl.setState(0);
                tpl.setUsed(0);
            }
        }

        info.setInfo(quans);

        return info;
    }
}
